package com.bub.pay.framework.shiro.authc;

import com.bub.pay.framework.common.util.EncryptionUtil;
import com.bub.pay.framework.common.util.SpringUtil;
import com.bub.pay.framework.redis.RedisClient;
import com.bub.pay.framework.redis.RedisKeyConstant;
import com.bub.pay.framework.redis.RedisKeyPrefix;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;

public class BcryptCredentialsMatcher implements CredentialsMatcher {

	private final static int LOGIN_FAILD_EXPIRE = 3600;
	private final static int MAX_LOGIN_FAILD = 5;

	@Override
	public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {

		boolean pwdCorrect = EncryptionUtil.matches(new String((char[]) token.getCredentials()),
				(String) info.getCredentials());
		if (pwdCorrect)
			return true;

		BNSimpleAuthenticationInfo bnSimpleAuthenticationInfo = (BNSimpleAuthenticationInfo) info;
		RedisClient redisClient = SpringUtil.getBean(RedisClient.class);
		int errorNum = 1;
		if (redisClient.exists(RedisKeyPrefix.USER,
				RedisKeyConstant.LOGIN_FAILD + bnSimpleAuthenticationInfo.getUserId())) {
			errorNum = (Integer) redisClient.get(RedisKeyPrefix.USER,
					RedisKeyConstant.LOGIN_FAILD + bnSimpleAuthenticationInfo.getUserId()) + 1;
		}
		redisClient.set(RedisKeyPrefix.USER, RedisKeyConstant.LOGIN_FAILD + bnSimpleAuthenticationInfo.getUserId(),
				errorNum, LOGIN_FAILD_EXPIRE);
		return false;
	}
}
